<template>
  <Head>
    <Meta property="og:image" :content="file.logoOg" />
    <Meta property="og:title" :content="$t('lotteryMoney.inviteLogotitle')" />
    <Meta
      property="og:description"
      :content="$t('lotteryMoney.inviteLogoDesc')"
    />
    <Meta name="twitter:image" :content="file.logoOg" />
    <Meta name="twitter:card" content="summary_large_image" />
  </Head>
  <div
    class="inviteFriends hideScrollBar"
    :class="{
      'inviteFriends-step0': step == 0,
      'inviteFriends-step1': step == 1,
    }"
    ref="scrollEl"
  >
    <!-- 导航 -->
    <NavBar
      style="flex: 1"
      :title="$t('lotteryMoney.zlhyzdj')"
      titleColor="#141924"
      isCusRightBtns
      isFixed
      :isShowLeft="step > 0"
      :customBackFn="handleBack"
    />
    <!-- 头部 -->
    <div v-if="step == 0" class="header">
      <!-- 背景 -->
      <img class="header-bg" src="/image/inviteFriends/v3-header-bg.png" />
      <!-- 瓜分奖池 -->
      <div class="header-title">
        {{ $t("lotteryMoney.djgf30jj").split("xxx")[0] }}
        <span class="header-title-value">30%</span>
        {{ $t("lotteryMoney.djgf30jj").split("xxx")[1] }}
      </div>
      <!-- 奖池 -->
      <div class="header-jctitle">{{ $t("lotteryMoney.jcje") }}</div>
      <!-- 奖池金额 -->
      <div class="header-jcvalue" v-if="shareInfo">
        = ${{ toThousands(decimalToLength(shareInfo.lastSuperPoolAmount)) }}
      </div>
      <div class="header-jcvalue" v-else>= ${{ 0.0 }}</div>
      <!-- 底部图标 -->
      <img class="header-bottom" src="/image/inviteFriends/v3-header-bt.png" />
    </div>
    <div v-else class="step1-bgcolor items-center">
      <div class="step1-bgcolor-item"></div>
      <div class="step1-bgcolor-item"></div>
    </div>

    <!-- 中间部分 -->
    <div v-if="step == 0" class="step0-box">
      <!-- 谷歌/facebook 授权注册 -->
      <div class="reward step0-top">
        <div class="reward-info">
          <!-- 免费下注 -->
          <div class="reward-info-item items-center">
            <div class="reward-info-item-text">
              {{ $t("lotteryMoney.mfxzText") }}
            </div>
            <div class="items-center">
              <div class="reward-info-item-value">
                +{{ (shareInfo && shareInfo.freeDrawPrizeCount) || 0 }}
              </div>
              <img class="reward-info-item-icon" src="/image/bet-blue.svg" />
            </div>
          </div>
          <!-- 赠金 -->
          <div class="reward-info-item items-center">
            <div class="reward-info-item-text">
              {{ $t("inviteFriends.bonusZj") }}
            </div>
            <div class="items-center">
              <div class="reward-info-item-value">+ 1000</div>
              <img class="reward-info-item-icon" src="/image/money-green.svg" />
            </div>
          </div>
          <!-- BDC -->
          <div class="reward-info-item items-center" style="margin-bottom: 0">
            <div class="reward-info-item-text">BDC</div>
            <div class="items-center">
              <div class="reward-info-item-value">
                + {{ (shareInfo && shareInfo.friendPrizeAmount) || 0 }}
              </div>
              <img class="reward-info-item-icon" src="/image/bdc2.svg" />
            </div>
          </div>
        </div>
        <!-- 底部 icon -->
        <img
          class="reward-bottom"
          src="/image/lottery-v3/inviteFriendsView-bt-img.svg"
        />
      </div>
      <!-- 注册你将获得 -->
      <div class="step0">
        <!-- 注册 -->
        <div class="register">
          <!-- 标题 -->
          <div class="register-title items-center">
            <img
              class="register-title-leftimg"
              src="/image/title-yellow-icon.svg"
            />
            <div class="register-title-text">
              {{ $t("inviteFriends.regist") }}
            </div>
            <img
              class="register-title-rightimg"
              src="/image/title-yellow-icon.svg"
            />
          </div>
          <!-- 授权 -->
          <div class="register-third items-center">
            <!-- 谷歌注册 -->
            <GoogleSign
              class="register-third-item items-center"
              style="background: #4dc995"
              @success="OnGoogleAuthSuccess"
            >
              <img
                class="register-third-item-logo"
                src="/image/google-icon.svg"
              />
              <div class="register-third-item-text">Google</div>
            </GoogleSign>
            <FacebookSign
              class="register-third-item items-center"
              style="background: #5697dc; margin-right: 0"
              @success="OnFacebookAuthSuccess"
              @error="OnFacebookAuthSuccess(false)"
            >
              <img
                class="register-third-item-logo"
                src="/image/facebook-icon.svg"
              />
              <div class="register-third-item-text">FaceBook</div>
            </FacebookSign>
          </div>
          <!-- or -->
          <div class="register-or items-center">
            <div class="register-or-left"></div>
            <div class="register-or-center">
              {{ $t("inviteFriends.hzText") }}
            </div>
            <div class="register-or-right"></div>
          </div>
          <!-- 邮箱 -->
          <van-field
            class="register-input"
            v-model="email"
            type="text"
            center
            clearable
            label=""
            :placeholder="$t('inviteFriends.qsrndyx')"
          >
          </van-field>
          <!-- 验证码 -->
          <van-field
            class="register-input register-yzm"
            v-model="yzm"
            type="digit"
            center
            clearable
            label=""
            :placeholder="$t('inviteFriends.qsryzm')"
            @blur="yzmwordBlur"
          >
            <template #button>
              <div class="register-send" @click="handleSend" v-if="time <= 0">
                {{ $t("inviteFriends.send") }}
              </div>
              <div class="register-send-nums" v-else>{{ time }}s</div>
            </template>
          </van-field>
          <!-- 动态加载的组件 -->
          <Hcaptcha
            v-if="isLoadHcap"
            ref="hcaptchaRef"
            eventType="lotteryV3-register"
            @verify="handleVerify"
          ></Hcaptcha>

          <!-- 验证码错误提示 -->
          <div v-if="errorAlertType == 2" class="errorAlert items-center">
            <img class="errorAlert-icon" src="/image/gth2.svg" />
            <div v-if="true" class="errorAlert-text">
              {{ $t("inviteFriends.yzmcw") }}
            </div>
            <div v-else class="errorAlert-yzmsx">
              {{ $t("inviteFriends.yzmsx") }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 设置密码 + 选择-地区 -->
    <div v-if="step == 1" class="step1-box">
      <div class="step1">
        <div class="reward step0-top">
          <div class="reward-info">
            <!-- 免费下注 -->
            <div class="reward-info-item items-center">
              <div class="reward-info-item-text">
                {{ $t("lotteryMoney.mfxzText") }}
              </div>
              <div class="items-center">
                <div class="reward-info-item-value">
                  +{{ (shareInfo && shareInfo.freeDrawPrizeCount) || 0 }}
                </div>
                <img class="reward-info-item-icon" src="/image/bet-blue.svg" />
              </div>
            </div>
            <!-- 赠金 -->
            <div class="reward-info-item items-center">
              <div class="reward-info-item-text">
                {{ $t("inviteFriends.bonusZj") }}
              </div>
              <div class="items-center">
                <div class="reward-info-item-value">+ 1000</div>
                <img
                  class="reward-info-item-icon"
                  src="/image/money-green.svg"
                />
              </div>
            </div>
            <!-- BDC -->
            <div class="reward-info-item items-center" style="margin-bottom: 0">
              <div class="reward-info-item-text">BDC</div>
              <div class="items-center">
                <div class="reward-info-item-value">
                  + {{ (shareInfo && shareInfo.friendPrizeAmount) || 0 }}
                </div>
                <img class="reward-info-item-icon" src="/image/bdc2.svg" />
              </div>
            </div>
          </div>
          <!-- 底部 icon -->
          <img
            class="reward-bottom"
            src="/image/lottery-v3/inviteFriendsView-bt-img.svg"
          />
        </div>
        <!-- 标题 -->
        <div class="register-title items-center" style="margin-top: 20px">
          <img
            class="register-title-leftimg"
            src="/image/title-yellow-icon.svg"
          />
          <div class="register-title-text">
            {{ $t("lotteryMoney.szdlmm") }}
          </div>
          <img
            class="register-title-rightimg"
            src="/image/title-yellow-icon.svg"
          />
        </div>

        <!-- 密码 -->
        <van-field
          class="step1-input"
          v-model="password"
          :type="passwordType"
          center
          label=""
          :placeholder="$t('inviteFriends.qsrmm')"
        >
          <template #button>
            <img
              class="step1-input-close"
              src="/image/close-000-icon.svg"
              @click="handlePasswordClose"
            />
            <img
              v-show="passwordType == 'password'"
              class="step1-input-bkj"
              src="/image/lotterymoney/free-mmbkj-icon.svg"
              @click="handlePasswordIskj(true)"
            />
            <img
              v-show="passwordType == 'text'"
              class="step1-input-kj"
              src="/image/lotterymoney/free-mmkj-icon.svg"
              @click="handlePasswordIskj(false)"
            />
          </template>
        </van-field>
        <div class="step1-alertItem items-center">
          <img
            v-show="!is6d15"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzsb-icon.svg"
          />
          <img
            v-show="is6d15"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzok-icon.svg"
          />
          <div class="step1-alertItem-text">
            {{ $t("lotteryMoney.zf6d15") }}
          </div>
        </div>
        <div class="step1-alertItem items-center">
          <img
            v-show="!isonesz"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzsb-icon.svg"
          />
          <img
            v-show="isonesz"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzok-icon.svg"
          />
          <div class="step1-alertItem-text">
            {{ $t("lotteryMoney.zsygsz") }}
          </div>
        </div>
        <div class="step1-alertItem items-center">
          <img
            v-show="!isonezm"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzsb-icon.svg"
          />
          <img
            v-show="isonezm"
            class="step1-alertItem-img"
            src="/image/lotterymoney/free-yzok-icon.svg"
          />
          <div class="step1-alertItem-text">
            {{ $t("lotteryMoney.zsygzm") }}
          </div>
        </div>
        <!-- 确认密码 -->
        <van-field
          class="step1-input"
          v-model="confirmPassword"
          :type="confirmPasswordType"
          center
          label=""
          :placeholder="$t('lotteryMoney.qzcsrmm')"
          @blur="confirmPasswordBlur"
        >
          <template #button>
            <img
              class="step1-input-close"
              src="/image/close-000-icon.svg"
              @click="handleConfirmPasswordClose"
            />
            <img
              v-show="confirmPasswordType == 'password'"
              class="step1-input-bkj"
              src="/image/lotterymoney/free-mmbkj-icon.svg"
              @click="handleConfirmPasswordTypeIskj(true)"
            />
            <img
              v-show="confirmPasswordType == 'text'"
              class="step1-input-kj"
              src="/image/lotterymoney/free-mmkj-icon.svg"
              @click="handleConfirmPasswordTypeIskj(false)"
            />
          </template>
        </van-field>

        <!-- 验证码错误提示 -->
        <div v-if="errorAlertType == 3" class="errorAlert items-center">
          <img class="errorAlert-icon" src="/image/gth2.svg" />
          <div class="errorAlert-text">
            {{ $t("lotteryMoney.mmbyz") }}
          </div>
        </div>

        <!-- 地区选择 -->
        <div class="step1-select items-center">
          <div class="step1-select-left">
            {{ $t("inviteFriends.dqText") }}
          </div>
          <div class="step1-select-right items-center" @click="showRegio">
            <FlagIcon
              v-if="areaCode"
              class="step1-select-icon"
              :iso="areaCode"
            />
            <div class="step1-select-code">{{ area }}</div>
            <img class="step1-select-btn" src="/image/jt-right-icon.svg" />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="footer items-center">
      <!-- 按钮 + 手指 -->
      <div class="footer-content" @click="nextClick">
        <!-- 按钮 -->
        <div class="footer-btn items-center">
          <img
            class="footer-btn-img"
            src="/image/lotterymoney/free-yy-btn-icon.svg"
          />
          <div class="footer-btn-text">
            {{ $t("lotteryMoney.ljzl") }}
          </div>
        </div>
        <!-- 手指 -->
        <img class="footer-sz" src="/image/lotterymoney/free-yysz-icon.svg" />
      </div>
    </div>

    <!-- 选择区域国旗 -->
    <SearchFlag
      v-model:show="isShowSearchFlag"
      @changeCode="changeCode"
    ></SearchFlag>
  </div>
</template>
<script setup name="inviteFriends">
import {
  toThousands,
  decimalToLength,
  navigateI18nTo,
  getOssFileUrl,
} from "@/utils";
import GoogleSign from "~~/components/google-sign/index.vue";
import FacebookSign from "~~/components/facebook-sign/index.vue";
import Hcaptcha from "~~/components/Hcaptcha/index.vue";
import {
  openID,
  containsEmail,
  hcaptchaValidateGetEmailCode,
  preValidation,
  validateTripartiteLogin,
  newMailboxRegisterCode,
} from "@/api/user";
import { getShareInfo, getJackpotShareInfo } from "@/api/inviteFriends";
import { useGlobalStore } from "~~/store/global";
import * as jwt from "jose";
import { useTripartiteStore } from "~~/store/modules/useTripartiteStore";
import { nation } from "~/config/nation";
import FlagIcon from "~~/components/flag-icon/index.vue";
import SearchFlag from "~~/components/invite-friends/search-flag.vue";

const { t } = useI18n();
const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  logo: "/image/inviteFriends/invite-friends-share-logo1.png",
  apiJs: "/file/auth2/api.js",
  sharePage: "invite-friends/share",
  logoOg: "/image/inviteFriends/invite-logo2.png",
});

/**
 * @description: 网站配置,用于分享页面场景
 */
useSeoMeta({
  title: t("lotteryMoney.inviteLogotitle"),
  description: t("lotteryMoney.inviteLogoDesc"),
  ogTitle: t("lotteryMoney.inviteLogotitle"),
  ogDescription: t("lotteryMoney.inviteLogoDesc"),
  // ogImage: file.logo,
  // ogUrl: file.sharePage,
  twitterTitle: t("lotteryMoney.inviteLogotitle"),
  twitterDescription: t("lotteryMoney.inviteLogoDesc"),
  // twitterImage: file.logo,
  // twitterCard: "summary",
});

// Google提供的reCAPTCHA服务的JavaScript API脚本。reCAPTCHA是一种用于区分人类用户和自动化程序（如机器人）的技术，常用于防止垃圾邮件和滥用行为。
useHead({
  script: [
    {
      src: file.apiJs,
    },
  ],
});

const globalStore = useGlobalStore();
const scrollEl = ref();
const route = useRoute();

console.log("页面参数:", route.query);
// firebase埋点
const firebase = useInitFirebase();
// 三方信息
const tripartiteState = useTripartiteStore();

// 获取页面信息
const shareInfo = ref(null);
const getShareInfoRequest = () => {
  getJackpotShareInfo({ inviteCode: route.query.code }).then((res) => {
    console.log("分享页面信息:", res);
    if (res) {
      shareInfo.value = res;
      shareInfo.value.freeDrawPrizeCount = res.friendFreeDrawPrizeCount || 0;
      shareInfo.value.friendPrizeAmount = res.friendPrizeAmount || 0;
    }
  });
};
// 步骤
const step = ref(0);

// 加载人机组件
const isLoadHcap = ref(false);

/***************** 地区展示 *****************/
const isShowSearchFlag = ref(false);
const area = ref(""); // 地区: +62
const areaCode = ref(null); // 区域 code
const chinese = ref(null); // 区域 名称

const showRegio = () => {
  isShowSearchFlag.value = true;
};
const changeCode = (val) => {
  console.log("选择了地区:", val);
  areaCode.value = val.code;
  area.value = `+${val.dialCode}`;
  chinese.value = val.chinese;
};

onMounted(() => {
  // 1.埋点
  firebase?.logEvent("BDC_H5_invite_friends_V3_Share_PUV");
  // 2. 获取页面信息
  getShareInfoRequest();

  isLoadHcap.value = true;

  // 4. 地区
  // globalStore.$state.publicArea = "62"; // zhjdebugger
  console.log("--globalStore.$state--", globalStore.$state);
  if (globalStore.$state.publicArea) {
    area.value = `+${globalStore.$state.publicArea}`;
    const areaInfo = Object.values(nation).find(
      (item) => item.dialCode == globalStore.$state.publicArea
    );
    areaCode.value = areaInfo?.code;
    chinese.value = areaInfo.chinese;
  }
});

onBeforeUnmount(() => {
  isLoadHcap.value = false;

  passwordWatch && passwordWatch();
});

/****************  获取-邮箱验证码  ****************/
const time = ref(0); // 倒计时
const timer = ref(); // 定时器
const hcaptchaRef = ref(); // 验证码实例
const hcaptchaToken = ref(""); //  googleToken

const handleSend = debounce(
  () => {
    // 先判断是否符合邮箱格式
    if (!email.value) return showToast(t("inviteFriends.qsryx"));
    if (!isEmail(email.value)) return showToast(t("inviteFriends.yxgsbzq"));
    //
    try {
      if (hcaptchaRef.value) {
        hcaptchaRef.value.execute();
      } else {
        isLoadHcap.value = true;
      }
    } catch (error) {
      console.error("error", error);

      showToast(t("inviteFriends.qsryx"));
    }
  },
  2000,
  false
);

// 获取邮箱验证码
const hcaptchaValidateGetEmailCodeApi = async (call) => {
  hcaptchaValidateGetEmailCode({
    email: email.value,
    type: 7,
    googleToken: hcaptchaToken.value,
  }).then((res) => {
    if (res) {
      call && call();
      nextTick(() => {
        hcaptchaToken.value = "";
        hcaptchaRef.value.reset && hcaptchaRef.value.reset(); // 没有起作用,就改了,跳转过去页面的返回按钮事件
        isLoadHcap.value = false;
      });
    }
  });
};

// 获取验证码
const handleSendmobileCode = () => {
  // 1. 获取验证码
  hcaptchaValidateGetEmailCodeApi(() => {
    // 2. 如果成功,执行定时器
    if (timer.value) return;
    time.value = 60;
    timer.value = setInterval(() => {
      time.value--;

      if (time.value <= 0) {
        isLoadHcap.value = true;
        clearInterval(timer.value);
        timer.value = undefined;
      }
    }, 1000);

    // 验证码发送埋点
    firebase?.logEvent("BDC_H5_invite_friends_YZM_PUV");
  });
};

/**
 * @description: 人机交互组件验证成功
 * @param {*} token 获取验证码使用的
 * @param {*} eKey
 */
const handleVerify = (token, eKey) => {
  // console.log("token--", token);
  // console.log("eKey--", eKey);
  // 1. 保存 token,用于获取 验证码
  hcaptchaToken.value = token;
  // 2. 获取验证码
  handleSendmobileCode();
};

/****************  三方授权: google + facebook  ****************/
// 是否使用,三方授权登录过
let isThreeParties = false;
const openIDApi = async (val) => {
  try {
    // 1. 使用 loading 遮罩
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
      zIndex: 999999999,
    });
    const result = await openID({
      openID: tripartiteState.openID,
    });
    // console.log("以往是否使用 openID 授权登录查询:", result);

    if (result) {
      // 已经注册过，提示
      if (result.openIdCheck) {
        registeredArr.push(val.email);
        tripartiteState.$patch({
          isUnregistered: true,
        });

        if (tripartiteState.$state.type == 3) {
          showToast(`Google ${t("inviteFriends.zhyzc")}`);
        } else if (tripartiteState.$state.type == 4) {
          showToast(`FaceBook ${t("inviteFriends.zhyzc")}`);
        }
      }
      // 未注册过
      else {
        tripartiteState.$patch({
          isUnregistered: false,
        });
        if (val && val.email) {
          // 1. 赋值 + 提示
          email.value = val.email;
          showToast(t("mvp.other.text12"));
          // 1.1
          hcaptchaToken.value = "";
          hcaptchaRef.value.reset && hcaptchaRef.value.reset(); // 没有起作用,就改了,跳转过去页面的返回按钮事件

          // 2. 授权成功,且没有注册的用户,直接跳转到注册页面
          isThreeParties = true;
          step.value = 1;
          firebase?.logEvent("BDC_H5_invite_friends_Step2_PUV"); // 埋点
        }
      }
    }
  } catch (error) {
    console.log(error);
  }
};

const OnGoogleAuthSuccess = (idToken) => {
  const info = jwt.decodeJwt(idToken.credential); //解析token
  tripartiteState.$patch({
    type: 3,
    idToken: idToken.credential,
    openID: info?.sub ?? "",
    email: info.email || "",
  });
  // console.log(idToken, "谷歌登录成功pageData", info);
  openIDApi(info);
};

//  facebook 授权以后是不返回邮箱的
const OnFacebookAuthSuccess = (response) => {
  if (response == false) {
    showToast(`FaceBook ${t("inviteFriends.sqsb")}`);
  } else {
    tripartiteState.$patch({
      type: 4,
      idToken: response.authResponse?.accessToken,
      openID: response.authResponse?.userID,
      email: response.email || "",
    });
    // console.log("facebook 登录成功pageData", response);
    openIDApi(response);
  }
};

/***************** 第 2 步  验证 *****************/
let containsEmailRule = null; // 邮箱后缀,支持的列表
containsEmail({}).then((res) => {
  if (res) {
    containsEmailRule = res;
  }
});
const email = ref(""); // 邮箱 berry@tradev-group.com
const yzm = ref(""); // 验证码
const nickName = ref("");
const registeredArr = []; // 记录,已经注册的邮箱
const errorAlertType = ref(1); // 1 不显示 2 验证码错误 3 密码不一致
// 验证邮箱验证码
let emailKey = "";
const registerClick = () => {
  if (!email.value) return showToast(t("inviteFriends.qsryx"));
  if (!isEmail(email.value)) return showToast(t("inviteFriends.yxgsbzq"));
  // 判断是否支持，不支持则提示  请输入正确的邮箱
  const list = email.value.split("@");
  const suffix = `@${list[1]}`;
  if (containsEmailRule && !containsEmailRule.includes(suffix)) {
    return showToast(t("inviteFriends.qsrzqdyxgs"));
  }
  // 账号(邮箱)是否已注册
  if (registeredArr.length > 0 && registeredArr.includes(email.value)) {
    return showToast(t("inviteFriends.zhyzc"));
  }
  // 验证码: 验证
  if (!yzm.value) return showToast(t("inviteFriends.qsryzm"));
  if (!yzm.value || `${yzm.value.length}` != 6 || !/^\d{6}$/.test(yzm.value)) {
    errorAlertType.value = 2;
    return showToast(t("inviteFriends.yzmcw"));
  }

  preValidation({
    type: 1,
    email: email.value,
    code: yzm.value,
  }).then((res) => {
    /****** start zhjdebugger start ******/
    // res = { key: "1111" };
    /****** end zhjdebugger end ******/

    if (res) {
      // 隐藏验证码错误提示
      if (errorAlertType.value != 1) errorAlertType.value = 1;
      //
      emailKey = res.key || "";

      step.value = 1;
      firebase?.logEvent("BDC_H5_invite_friends_Step2_PUV"); // 埋点
    } else {
      errorAlertType.value = 2;
    }
  });
};

const yzmwordBlur = (val) => {
  console.log("yzmwordBlur:", yzm.value);
  if (!yzm.value || yzm.value == "") {
    errorAlertType.value = 1;
  }
};

/**************** 第 3 步 设置密码 ****************/
// 密码格式校验
const is6d15 = ref(false); // 6 到 15 位
const isonezm = ref(false); // 至少一个字母
const isonesz = ref(false); // 至少一个数字

const password = ref("");
const passwordType = ref("password");
// 正则 6 到 15 位, 包含 6 和 15
function validateLength(str) {
  const one = /^.{6,15}$/.test(str);
  const two = /^([A-Za-z0-9]{6,15})$/.test(str);
  console.log(one, "--", two);

  return one && two;
}
function containsNumber(str) {
  const regex = /\d/;
  return regex.test(str);
}
function containsLetter(str) {
  const regex = /[a-zA-Z]/;
  return regex.test(str);
}

const passwordBlur = (val) => {
  console.log("passwordBlur:", password.value);
  if (password.value) {
    is6d15.value = validateLength(password.value);
    isonesz.value = containsNumber(password.value);
    isonezm.value = containsLetter(password.value);
  } else {
    is6d15.value = false;
    isonesz.value = false;
    isonezm.value = false;
  }
};

const passwordWatch = watch(
  () => password.value,
  (val) => {
    passwordBlur();
  }
);

const handlePasswordClose = () => {
  password.value = "";
};

const handlePasswordIskj = (val) => {
  if (passwordType.value == "password" && val) {
    passwordType.value = "text";
  } else {
    passwordType.value = "password";
  }
};

const confirmPassword = ref("");
const confirmPasswordType = ref("password");
const confirmPasswordBlur = (val) => {
  console.log("confirmPasswordBlur:", confirmPassword.value);
  if (password.value != confirmPassword.value) {
    errorAlertType.value = 3;
  } else {
    errorAlertType.value = 1;
  }
};
const handleConfirmPasswordClose = () => {
  confirmPassword.value = "";
  errorAlertType.value = 1;
};
const handleConfirmPasswordTypeIskj = (val) => {
  if (confirmPasswordType.value == "password" && val) {
    confirmPasswordType.value = "text";
  } else {
    confirmPasswordType.value = "password";
  }
};

/**************** 第 4 步 注册 ****************/
// 三方授权注册
const validateTripartiteLoginApi = async (call) => {
  // console.log("三方授权注册逻辑", tripartiteState.$state);
  // return;
  const result = await validateTripartiteLogin({
    areaCode: area.value,
    areaName: chinese.value,
    email: email.value,
    inviteId: route.query.code ?? "", // 邀请ID
    nickname: nickName.value,
    password: password.value,
    type: tripartiteState.type,
    openID: tripartiteState.openID,
    idToken: tripartiteState.idToken,
    userSource: 12,
    // emailStatus: tripartiteState.email == email.value ? "0" : "1", // 增加以后,接口报错,请联系管理员
  });
  if (result) {
    globalStore.$patch({
      token: result?.user?.token ?? "",
    });
    // 注册成功
    showToast(t("inviteFriends.zccg"));
    // 三方注册,埋点
    firebase?.logEvent("BDC_H5_invite_friends_SFZC_PUV");
    call && call(true);
  } else {
    call && call(false);
  }
};
// 邮箱注册
const newMailboxRegisterApi = async (call) => {
  // console.log("邮箱注册 - 逻辑");
  // return;

  const result = await newMailboxRegisterCode({
    areaCode: area.value,
    areaName: chinese.value,
    email: email.value,
    inviteId: route.query.code ?? "", // 邀请ID
    nickname: nickName.value,
    password: password.value,
    lastLoginIp: globalStore.$state.publicIp ?? "",
    userSource: 12,
    key: emailKey || "", // newMailboxRegisterCode: 邮箱验证成功的 key
  });

  if (result && result != 1003) {
    globalStore.$patch({
      token: result?.user?.token ?? "",
    });
    // 注册成功
    showToast(t("inviteFriends.zccg"));
    // 邮箱注册,埋点
    firebase?.logEvent("BDC_H5_invite_friends_EmailZC_PUV");
    call && call(true);
  } else if (result == 1003) {
    // 提示邮箱已经注册过
    showToast(t("inviteFriends.yxyjzc"));
    call && call(true);
  } else {
    call && call(false);
  }
};
/**************** 下一步 ****************/
const nextClick = () => {
  if (step.value == 1) {
    if (password.value) {
      if (!confirmPassword.value) {
        return showToast(t("lotteryMoney.qzcsrmm"));
      }
      if (is6d15.value && isonesz.value && isonezm.value) {
        if (confirmPassword.value == password.value) {
          firebase?.logEvent("BDC_H5_invite_friends_Step3_PUV"); // 埋点
        }
      }
    } else {
      return showToast(t("inviteFriends.qsrmm"));
    }

    // 0. 请选择地区
    if (!area.value) return showToast(t("inviteFriends.qxzdq"));
    // 0.1 如果没有名称,默认是邮箱前缀
    const list = email.value.split("@");
    if (!nickName.value) nickName.value = list[0];
    // 0.2 统一遮罩
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
      zIndex: 999999999,
    });
    // 2. 跳转,下载页面
    const call = (isSuccess) => {
      if (!isSuccess) {
        firebase?.logEvent("BDC_H5_invite_friends_ZcFail_PUV"); // 埋点
      }
      navigateI18nTo({
        path: "/invite-friends/v3/download-app",
        query: {
          freeCount: shareInfo.value.freeDrawPrizeCount,
          freeBdc: shareInfo.value.friendPrizeAmount,
          sourceType: 12,
        },
      });
    };
    // 1. 第三方注册接口
    if (isThreeParties) {
      if (!tripartiteState.$state.isUnregistered) {
        validateTripartiteLoginApi(call);
      } else {
        if (tripartiteState.$state.type == 3) {
          showToast(`Google ${t("inviteFriends.zhyzc")}`);
        } else if (tripartiteState.$state.type == 4) {
          showToast(`FaceBook ${t("inviteFriends.zhyzc")}`);
        }
      }
    }
    // 1.1 用户手动输入的邮箱,调用这个接口注册
    else {
      newMailboxRegisterApi(call);
    }
  } else if (step.value == 0) {
    registerClick();
  }
};

/****************** start 自定义返回 start ******************/
const handleBack = () => {
  if (step.value > 0) {
    step.value -= 1;
  }
};
</script>
<style lang="scss" scoped>
.inviteFriends {
  position: relative;
  overflow-y: scroll;
  overflow-x: hidden;
  height: 100vh;
  &-step0 {
    background-color: #fff;
  }
  &-step1 {
    background-color: #faf4f0;
  }
}

.header {
  position: relative;
  width: 100vw;
  height: 168 * 2px;
  overflow: hidden;

  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
  }

  &-title {
    position: relative;
    z-index: 9;
    width: 96vw;
    padding: 18 * 2px 2vw 15 * 2px 2vw;

    text-align: center;
    color: #002853;
    font-size: 13 * 2px;
    font-weight: 700;

    &-value {
      color: #d5602e;
      font-size: 13 * 2px;
      font-weight: 700;
    }
  }

  &-jctitle {
    position: relative;
    z-index: 9;

    width: 100vw;
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    font-size: 11 * 2px;
    font-weight: 590;
  }

  &-jcvalue {
    position: relative;
    z-index: 9;
    margin-top: 3 * 2px;

    width: 100vw;
    text-align: center;
    color: #fff;
    font-size: 18 * 2px;
    font-weight: 1000;
  }

  &-bottom {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 10 * 2px;
    width: 322 * 2px;
    height: 11 * 2px;
  }
}

.reward {
  &-info {
    padding: 12 * 2px 10 * 2px;
    border-radius: 8 * 2px;
    border: 1px dashed #ff9b01;
    background: #fff5e5;
    width: 100%;

    &-item {
      justify-content: space-between;
      margin-bottom: 19 * 2px;

      &-text {
        color: #807666;
        font-size: 15 * 2px;
        font-weight: 510;
      }

      &-value {
        color: #d5602e;
        font-size: 17 * 2px;
        font-weight: 700;
      }

      &-icon {
        width: 20 * 2px;
        height: 20 * 2px;
        margin-left: 10 * 2px;
      }
    }
    &-line {
      width: 0.5px;
      height: 18 * 2px;
      background-color: rgba(115, 119, 128, 0.15);
    }
  }
  &-bottom {
    margin-left: calc((100% - 322 * 2px) / 2);
    width: 322 * 2px;
    height: 11 * 2px;
  }
}
.step0 {
  &-box {
    position: relative;
    margin-top: -10 * 2px;
    margin-bottom: 15 * 2px;
    padding: 10 * 2px 15 * 2px;
    background-color: #fff;
    border-top-left-radius: 12 * 2px;
    border-top-right-radius: 12 * 2px;
  }

  &-top {
    margin-bottom: 10 * 2px;
  }
}

.step1 {
  position: relative;
  z-index: 3;
  padding: 15 * 2px 10 * 2px;
  background-color: #fff;
  width: 100%;
  border-radius: 12 * 2px;
  box-shadow: 0px 16px 24 * 2px 0px rgba(0, 33, 68, 0.08);

  &-box {
    padding: 20 * 2px 15 * 2px;
  }

  &-bgcolor {
    position: absolute;
    top: 160 * 2px;
    width: 100vw;
    justify-content: space-around;

    &-item {
      width: 140 * 2px;
      height: 140 * 2px;
      background-color: #ff9b01;
      filter: blur(120 * 2px);
    }
  }

  &-title {
    background: linear-gradient(
      90deg,
      rgba(254, 255, 221, 0) 0%,
      #feffdd 50.18%,
      rgba(254, 255, 221, 0) 100%
    );
    text-align: center;
    font-size: 12 * 2px;
    font-weight: 590;
    width: 343 * 2px;
    padding: 2 * 2px 0;
    color: #0058b7;
  }

  &-ht {
    width: 380 * 2px;
  }
  &-yzm {
    padding: 6 * 2px 10 * 2px;
  }
  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    background: linear-gradient(180deg, #e7fbff 0%, #fff 100%);
    width: 100%;
    height: 88 * 2px;
  }

  &-input {
    border-radius: 4 * 2px;
    background: #f0f5fa;
    margin-top: 12 * 2px;
    color: #c2c5cc;
    font-size: 15 * 2px;
    font-weight: 400;
    &-close {
      margin-left: 10 * 2px;
      width: 22 * 2px;
      height: 22 * 2px;
    }
    &-bkj {
      margin-left: 10 * 2px;
      width: 22 * 2px;
      height: 22 * 2px;
    }
    &-kj {
      margin-left: 10 * 2px;
      width: 22 * 2px;
      height: 22 * 2px;
    }
  }

  &-alertItem {
    margin-top: 6 * 2px;
    &-img {
      width: 14 * 2px;
      height: 14 * 2px;
      margin-right: 6 * 2px;
    }
    &-text {
      font-size: 11 * 2px;
      color: #999da7;
    }
  }

  &-select {
    padding: 12 * 2px 15 * 2px;
    justify-content: space-between;
    border-radius: 4 * 2px;
    background: #f0f5fa;
    margin-top: 10 * 2px;

    &-left {
      color: #999da7;
      font-size: 15 * 2px;
    }
    &-right {
      margin-left: 8 * 2px;
      height: 10 * 2px;
    }
    &-code {
      margin-left: 8 * 2px;
      color: #17191a;
      font-size: 15 * 2px;
    }
    &-icon {
      width: 28 * 2px !important;
      height: 18 * 2px !important;
    }
    &-btn {
      margin-left: 12 * 2px;
      height: 10 * 2px;
    }
  }
}

.register {
  position: relative;
  z-index: 3;
  padding: 15 * 2px 10 * 2px;
  background-color: #fff;
  width: 100%;
  border-radius: 12 * 2px;
  box-shadow: 0px 16px 24 * 2px 0px rgba(0, 33, 68, 0.08);

  &-ht {
    position: relative;
    z-index: 2;
    width: 380 * 2px;
  }
  &-yzm {
    margin-bottom: 0 !important;
    padding-top: 6 * 2px;
    padding-bottom: 6 * 2px;
  }
  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    background: linear-gradient(180deg, #e7fbff 0%, #fff 100%);
    width: 100%;
    height: 88 * 2px;
  }

  &-title {
    position: relative;
    z-index: 9;
    justify-content: center;
    margin-bottom: 15 * 2px;
    &-leftimg {
      margin-top: 3 * 2px;
      height: 9 * 2px;
      margin-right: 10 * 2px;
    }
    &-rightimg {
      margin-top: 3 * 2px;
      height: 9 * 2px;
      margin-left: 10 * 2px;
    }
    &-text {
      color: #002853;
      font-size: 17 * 2px;
      font-weight: 590;
      text-align: center;
    }
  }
  &-third {
    margin-bottom: 10 * 2px;
    &-item {
      border-radius: 4 * 2px;
      padding: 6 * 2px 20 * 2px;
      overflow: hidden;
      justify-content: center;
      width: calc(50% - 6 * 2px);
      margin-right: 12 * 2px;
      &-logo {
        width: 30 * 2px;
        height: 30 * 2px;
        margin-right: 8 * 2px;
      }
      &-text {
        font-size: 15 * 2px;
        font-weight: 510;
        color: #fff;
      }
    }
  }

  &-or {
    justify-content: center;
    margin-bottom: 10 * 2px;
    &-left {
      flex: 1;
      height: 1px;
      background: linear-gradient(
        90deg,
        rgba(255, 255, 255, 0) 0%,
        #f0f3fa 100%
      );
    }
    &-center {
      margin: 0 15 * 2px;
      color: #141924;
      text-align: center;
      font-size: 14 * 2px;
      font-weight: 400;
    }
    &-right {
      flex: 1;
      height: 1px;
      background: linear-gradient(
        90deg,
        #f0f3fa 0%,
        rgba(255, 255, 255, 0) 100%
      );
    }
  }

  &-input {
    border-radius: 4 * 2px;
    background: #f0f5fa;
    margin-bottom: 12 * 2px;
    color: #c2c5cc;
    font-size: 15 * 2px;
    font-weight: 400;
  }
  &-btn {
    background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
    box-shadow: 0px -8px 8px 0px rgba(0, 0, 0, 0.25) inset;
    width: 100%;
    border-radius: 100px;
    padding: 12 * 2px 0;
    text-align: center;
    color: #fff;
    font-size: 17 * 2px;
    font-weight: 590;
  }

  &-send {
    padding: 8px 12px;
    border-radius: 4 * 2px;
    background: #ff9b01;
    color: #fff;
    font-weight: 590;
    font-size: 15 * 2px;
    margin-left: 10 * 2px;
    &-nums {
      padding: 8px 12px;
      border-radius: 4 * 2px;
      background: #b0d1f4;
      color: #fff;
      font-weight: 590;
      font-size: 15 * 2px;
      margin-left: 10 * 2px;
    }
  }
}

.footer {
  position: relative;
  margin-left: 25 * 2px;
  width: calc(100vw - 25 * 4px);
  z-index: 19;
  justify-content: center;

  &-btn {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    -webkit-transform: translateX(-50%); /* Safari 和 iOS 浏览器 */
    justify-content: center;
    transform-origin: bottom left;

    @keyframes scalebtn {
      0% {
        transform: scale(1) translateX(-50%);
      }
      50% {
        transform: scale(1.15) translateX(-50%);
      }

      100% {
        transform: scale(1) translateX(-50%);
      }
    }
    animation: scalebtn 0.7s linear infinite alternate;
    &-img {
      width: 343 * 2px;
      min-height: 40 * 2px;
    }

    &-text {
      position: absolute;
      z-index: 9;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      font-size: 17 * 2px;
      font-weight: 860;
    }
  }
  &-sz {
    position: absolute;
    top: 25 * 2px;
    transform: translateX(290px);
    width: 53 * 2px;
    height: 45 * 2px;

    @keyframes fluctuation {
      0% {
        transform: translate(290px, -25%);
      }
      100% {
        transform: translate(290px, 20%);
      }
    }
    animation: fluctuation 0.4s linear infinite alternate;
  }
}

.errorAlert {
  margin-top: 10 * 2px;

  &-icon {
    width: 18 * 2px;
    height: 18 * 2px;
    margin-right: 2 * 2px;
  }
  &-text {
    color: #ff4040;
    font-size: 11 * 2px;
  }
}
</style>
